package chase.java.readData;

import chase.java.unit.Edge;
import chase.java.unit.Point;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class JsonReader {

    public static List<Edge> reader(String filePath){

        List<Edge> edges = new ArrayList<>();

        //JS字符串
        File file = new File(filePath);
        BufferedReader fis = null;
        StringBuilder jsonStr = new StringBuilder();
        try {
           fis  = new BufferedReader(new FileReader(file));

            String line;
            while((line = fis.readLine()) != null){
                jsonStr.append(line).append("\n");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if(fis != null){
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        //处理JS字符串
        JSONObject jsonObj = JSONObject.fromObject(jsonStr.toString());
        JSONArray features = (JSONArray) jsonObj.get("features");

        for (Object feature : features) {
            JSONObject street = (JSONObject) feature;
            JSONObject geometry = (JSONObject) street.get("geometry");
            JSONArray paths = (JSONArray) geometry.get("paths");
            //对道路进行解析
            for (Object o : paths) {
                Edge edge = new Edge();
                JSONArray path = (JSONArray) o;
                for (Object value : path) {
                    String lon = ((JSONArray) value).get(0).toString();
                    String lat = ((JSONArray) value).get(1).toString();
                    edge.add(new Point(Double.parseDouble(lon), Double.parseDouble(lat)));
                }
                edges.add(edge);
            }

        }

        return edges;
    }

}
